package com.myjdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class UserDao {

    // 静态方法：获取数据库连接
    public static Connection getConnection() {
        Connection cnn = null;
        try {

            // 1. 加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("驱动加载成功");

            // 2. 创建连接
            String url = "jdbc:mysql://localhost:3306/db01?useSSL=false&serverTimezone=Asia/Shanghai";
            String user = "root";
            String password = "a15207291068";
            System.out.println("正在连接数据库...");

            cnn = DriverManager.getConnection(url, user, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace(); // 注册驱动类失败
        } catch (SQLException e) {
            e.printStackTrace(); // 获取连接失败
        }
        return cnn;
    }

    // 静态方法：获取所有用户记录
    public static List<User> getAllRecorder() {
        List<User> li = new ArrayList<>(); //
        Connection cnn = getConnection(); // 获取连接
        String sql = "select * from user"; //
        Statement stmt = null;
        ResultSet rs = null;

        try {
            stmt = cnn.createStatement(); //
            rs = stmt.executeQuery(sql); //

            // 遍历结果集
            while (rs.next()) { //
                User u = new User(); //
                u.setId(rs.getInt("id")); //
                u.setUsername(rs.getString("username")); //
                u.setUserpwd(rs.getString("userpwd")); //
                u.setTruename(rs.getString("truename")); //
                li.add(u); //
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 释放资源 (非常重要！)
            try {
                if (rs != null) {
                    rs.close(); //
                }
                if (stmt != null) {
                    stmt.close(); //
                }
                if (cnn != null) {
                    cnn.close(); //
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return li; //
    }
}



